package com.example.chenduoyun.safe.activity;
/**
 * @author cdy
 */

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.chenduoyun.safe.R;
import com.example.chenduoyun.safe.utils.ConstantValue;
import com.example.chenduoyun.safe.utils.SpUtils;
import com.example.chenduoyun.safe.utils.StreamUtil;
import com.example.chenduoyun.safe.utils.ToastUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class SplashActivity extends AppCompatActivity {
    private static final String TAG = "SplashActivity";
    /**
     * 更新状态码 UPDATE_VERSION
     * 进入主界面码 ENTER_HOME
     * url报错 URL_ERROR
     * io报错 IO_ERROR
     * json报错 JSON_ERROR
     */
    private static final int UPDATE_VERSION = 100;
    private static final int ENTER_HOME = 101;
    private static final int URL_ERROR = 102;
    private static final int IO_ERROR = 103;
    private static final int JSON_ERROR = 104;
    private TextView tvVersionName;
    private int mLocalVersionCode;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_VERSION:
                    showUpdateDialog();
                    break;
                case ENTER_HOME:
                    enterHome();
                    break;
                case URL_ERROR:
                    ToastUtil.show(SplashActivity.this, "url异常");
                    enterHome();
                    break;
                case IO_ERROR:
                    ToastUtil.show(SplashActivity.this, "IO异常");
                    enterHome();
                    break;
                case JSON_ERROR:
                    ToastUtil.show(SplashActivity.this, "JSON异常");
                    enterHome();
                    break;
                default:
                    break;
            }
        }
    };
    private RelativeLayout rl_root;

    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.drawable.home_apps);
        builder.setTitle("版本更新");
        builder.setMessage("有新的版本更新，更新内容有。。。。。。");
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                downloadApk();
            }
        });
        builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                enterHome();
            }
        });

        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                enterHome();
                dialog.dismiss();
            }
        });

        builder.show();
    }

    private void downloadApk() {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            String path = Environment.getExternalStorageDirectory().getAbsolutePath() +
                    File.separator + "sdy.apk";
            HttpUtils httpUttils = new HttpUtils();

            httpUttils.download("asd", path, new RequestCallBack<File>() {
                @Override
                public void onSuccess(ResponseInfo<File> responseInfo) {
                    Log.i(TAG, "下载成功");
                    File file = responseInfo.result;
                    installApk(file);
                }

                @Override
                public void onFailure(HttpException e, String s) {
                    Log.i(TAG, "下载失败");
                }

                @Override
                public void onStart() {
                    Log.i(TAG, "下载开始");
                    super.onStart();
                }

                @Override
                public void onLoading(long total, long current, boolean isUploading) {
                    Log.i(TAG, "下载成功total " + total + "    current" + current + "   isUploading" + isUploading);
                    super.onLoading(total, current, isUploading);
                }
            });
        }

    }

    /**
     * 安装APK
     *
     * @param file
     */
    private void installApk(File file) {
        Intent intent = new Intent("android.intent.action.VIEW");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setDataAndType(Uri.fromFile(file),
                "application/vnd.android.package-archive");
        //startActivity(intent);
        startActivityForResult(intent, 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        enterHome();
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void enterHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_splash);
        initUI();
        initData();
        initAnimation();
    }

    private void initAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(0, 1);
        alphaAnimation.setStartTime(1000);
        rl_root.startAnimation(alphaAnimation);
    }

    /**
     * 初始化数据
     */
    private void initData() {
        tvVersionName.setText("版本名称:" + getVersionName());
        mLocalVersionCode = getVersionCode();
        if(SpUtils.getBoolean(this, ConstantValue.OPEN_UPDATE,false)) {
            checkVersion();
        }else{
            mHandler.sendEmptyMessageDelayed(ENTER_HOME,1000);
        }
    }

    private void checkVersion() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = Message.obtain();
                long startTime = System.currentTimeMillis();
                try {
                    msg.what = ENTER_HOME;
                    if (false) {
                        URL url = new URL("http://192.0.2.2:8080/update.json");
                        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                        connection.setConnectTimeout(2000);
                        connection.setReadTimeout(2000);
                        if (connection.getResponseCode() == 200) {
                            InputStream is = connection.getErrorStream();
                            String json = StreamUtil.streamToString(is);
                            Log.i(TAG, json);

                            JSONObject jsonObject = new JSONObject(json);

                            String versionName = jsonObject.getString("versionName");
                            Log.i(TAG, versionName);
                            String versionDes = jsonObject.getString("versionDes");
                            Log.i(TAG, versionDes);
                            String versionCode = jsonObject.getString("versionCode");
                            Log.i(TAG, versionCode);
                            String downloadUrl = jsonObject.getString("downloadUrl");
                            Log.i(TAG, downloadUrl);
                            if (Integer.parseInt(versionCode) > mLocalVersionCode) {
                                //提示更新
                                msg.what = UPDATE_VERSION;
                            } else {
                                //进入主页
                                msg.what = ENTER_HOME;
                            }
                        }
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    msg.what = URL_ERROR;
                } catch (IOException e) {
                    e.printStackTrace();
                    msg.what = IO_ERROR;
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.what = JSON_ERROR;
                } finally {
                    long endTime = System.currentTimeMillis();
                    if (endTime - startTime < 2000) {
                        try {
                            Thread.sleep(2000 - endTime + startTime);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    mHandler.sendMessage(msg);
                }
            }
        }).start();

    }

    /**
     * 初始化UI
     */
    private void initUI() {
        tvVersionName = findViewById(R.id.tv_version_name);
        rl_root = findViewById(R.id.rl_root);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    public String getVersionName() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo mPackageInfo = pm.getPackageInfo(getPackageName(), 0);
            return mPackageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int getVersionCode() {
        PackageManager pm = getPackageManager();
        try {
            PackageInfo mPackageInfo = pm.getPackageInfo(getPackageName(), 0);
            return mPackageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
